package com.zhang.zhangapp.view.shop;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.ImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.zaaach.citypicker.model.LocateState;
import com.zhang.zhangapp.LoginActivity;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.config.HttpConfig;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.ZFile;
import com.zhang.zhangapp.bean.shop.ShopDetail;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.utils.PicassoImageLoader;
import com.zhang.zhangapp.utils.ScreenUtils;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.BaseAppCompatActivityActivity;
import com.zhang.zhangapp.view.CommonWebViewActivity;
import com.zhang.zhangapp.view.ImagePreviewActivity;
import com.zhang.zhangapp.view.adapter.BannerPagerAdapter;
import com.zhang.zhangapp.view.adapter.CommentAdapter;
import com.zhang.zhangapp.view.adapter.ShopCharacteristicAdapter;
import com.zhang.zhangapp.view.custom.HorizontalListView;
import com.zhang.zhangapp.view.custom.IndicatorView;
import com.zhang.zhangapp.view.custom.ListViewInScrollView;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/10.
 */
@ContentView(R.layout.activity_shop_detail)
public class ShopDetailActivity extends BaseAppCompatActivityActivity {

    private final static int CALL_PHONE = 2;

    @ViewInject(R.id.index_detail_viewpager)
    ViewPager viewPager;
    @ViewInject(R.id.detail_indicator)
    IndicatorView indicatorView;
    @ViewInject(R.id.detail_shop_name)
    TextView shopNameText;
    @ViewInject(R.id.detail_shop_location)
    TextView shopLocationText;
    @ViewInject(R.id.detail_has_sale)
    TextView scaleCountText;
    @ViewInject(R.id.cash_coupon_scale_count)
    TextView cashCoupoonScaleCountText;
    @ViewInject(R.id.cash_coupon_title)
    TextView cashCouponTitleText;
    @ViewInject(R.id.cash_coupon_price)
    TextView cashCouponPriceText;
    @ViewInject(R.id.shop_detail_characteristic)
    HorizontalListView characteristicListView;
    @ViewInject(R.id.user_comment_listview)
    ListViewInScrollView commentListView;
    @ViewInject(R.id.scrollView)
    ScrollView scrollView;
    @ViewInject(R.id.detail_shop_cash_coupon_price)
    TextView cashCouponScalePriceText;
    @ViewInject(R.id.coupon_layout)
    LinearLayout couponLayout;
    @ViewInject(R.id.commnet_more)
    TextView commentMoreText;//查看更多
    @ViewInject(R.id.user_comment_text)
    TextView userCommentText;//我来评价
    ShopDetail shopDetail;
    List<ZFile> characteristicFileList = new ArrayList<>();
    private BannerPagerAdapter mBannerPagerAdapter;

    private List<ZFile> pictureList = new ArrayList<>();

    Handler scrollViewHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_UP);
        }
    };

    private String shopCode;
    private String couponFaceVal = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        shopCode = getIntent().getStringExtra("shopCode");
        couponFaceVal = getIntent().getStringExtra("faceval");
        getShopDetail();
    }

    @Event(type = View.OnClickListener.class, value = {R.id.action_bar_left_image, R.id.action_bar_right_image, R.id.detail_pay_money
            , R.id.detail_buy_coupon, R.id.detail_shop_tel, R.id.shop_detail_layout, R.id.user_comment_text, R.id.commnet_more})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.action_bar_left_image:
                this.finish();
                break;
            case R.id.action_bar_right_image:
                collectShop();
                break;
            case R.id.detail_pay_money:
                openPayOrder();
                break;
            case R.id.detail_buy_coupon:
                openBuyCouponActivity();
                break;
            case R.id.detail_shop_tel: {
                call(shopDetail.getPhone());
            }
            break;
            case R.id.shop_detail_layout:
                openDetailH5();
                break;
            case R.id.user_comment_text:
                openCommentActivity();
                break;
            case R.id.commnet_more:
                openCommentListActivity();
                break;
        }
    }

    private void openCommentListActivity() {
        if (MApplication.getInstance().getUser() == null) {
            goLoginActivity();
        } else {
            Intent intent = new Intent(this, CommentListActivity.class);
            intent.putExtra("shopCode", shopDetail.getShopCode());
            startActivity(intent);
        }
    }

    private void openCommentActivity() {
        if (MApplication.getInstance().getUser() == null) {
            goLoginActivity();
        } else {
            Intent intent = new Intent(this, UserCommentActivity.class);
            intent.putExtra("shopCode", shopDetail.getShopCode());
            startActivity(intent);
        }
    }

    private void openPayOrder() {
        if (MApplication.getInstance().getUser() == null) {
            goLoginActivity();
        } else {
            Intent intent = new Intent(this, PayOrderActivity.class);
            intent.putExtra("shop", shopDetail);
            intent.putExtra("faceval", couponFaceVal);
            startActivity(intent);
        }
    }

    private void openBuyCouponActivity() {
        if (MApplication.getInstance().getUser() == null) {
            goLoginActivity();
        } else {
            Intent intent = new Intent(this, BuyCouponActivity.class);
            intent.putExtra("ticket", shopDetail.getTicket());
            intent.putExtra("shopCode", shopDetail.getShopCode());
            startActivity(intent);
        }
    }

    private void goLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
    }


    private void openDetailH5() {
        Intent intent = new Intent(this, CommonWebViewActivity.class);
        intent.putExtra("url", shopDetail.getShopdetail());
        intent.putExtra("title", shopDetail.getShopName());
        startActivity(intent);

    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码  模拟器、虚拟机会报错
     */
    private void call(String phone) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
        } else {
            startCall();
        }
    }

    /**
     * 获取店铺详情
     */
    private void getShopDetail() {
        if (showLoadingDialog()) {
            Map<String, String> params = new HashMap<>();
            params.put("shopCode", shopCode);
            CommonHttp.commonHttp("hzg/shop/queryDetail", params, new MCallback() {
                @Override
                public void onSuccess(String data) {
                    try {
                        Gson gson = new Gson();
                        shopDetail = gson.fromJson(data, ShopDetail.class);
                        initViewPager();
                        initView();
                        initCharacteristic();
                        initCommentView();
                        scrollViewHandler.postDelayed(runnable, 200);
                    } catch (Exception e) {
                    }
                }

                @Override
                public void onSuccess(String message, String code) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    dismisionDalog();
                }
            });
        }
    }

    /**
     * 收藏店铺
     */
    private void collectShop() {
        if (showLoadingDialog()) {
            Map<String, String> params = new HashMap<>();
            params.put("shopCode", shopDetail.getShopCode());
            params.put("memberId", MApplication.getInstance().getUser().getMemberId());
            CommonHttp.commonHttp("hzg/shop/shopCollec", params, new MCallback() {
                @Override
                public void onSuccess(String data) {
                    T.showShort(ShopDetailActivity.this, "收藏成功");
                }

                @Override
                public void onSuccess(String message, String code) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    dismisionDalog();
                }
            });
        }
    }

    /**
     * 初始化顶部图片
     */
    private void initViewPager() {
        if (shopDetail.getDoorpics() != null) {
            pictureList.clear();
            String[] imgs = shopDetail.getDoorpics().split(",");
            for (String img : imgs) {
                ZFile file = new ZFile();
                file.setPicurl(HttpConfig.IMAGE_HTTP_PATH + img);
                pictureList.add(file);
            }
        }
        mBannerPagerAdapter = new BannerPagerAdapter(this, pictureList);
        viewPager.setAdapter(mBannerPagerAdapter);
        indicatorView.setViewPager(pictureList.size(), viewPager);
        viewPager.setCurrentItem(0);
    }


    private void initView() {
        shopNameText.setText(shopDetail.getShopName());
        scaleCountText.setText("已出售" + shopDetail.getConsumecon());
        shopLocationText.setText(shopDetail.getAddress());
        if (shopDetail.getTicket() != null && shopDetail.getTicket().getFactval()!=null &&!shopDetail.getTicket().getFactval().equals("") && !shopDetail.getTicket().getFactval().equals("0")) {
            cashCoupoonScaleCountText.setText(shopDetail.getTicket().getDescr());
            cashCouponPriceText.setText("门市价: " + shopDetail.getTicket().getFaceval() + "元");
            cashCouponScalePriceText.setText(shopDetail.getTicket().getFactval());
        } else {
            couponLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        startCall();
    }

    private void startCall() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + shopDetail.getPhone()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 初始化特色
     */
    private void initCharacteristic() {

        if (shopDetail.getFeature() != null) {
            initImagePicker();
            String[] imgs = shopDetail.getDoorpics().split(",");
            for (String img : imgs) {
                ZFile file = new ZFile();
                file.setPicurl(HttpConfig.IMAGE_HTTP_PATH + img);
                characteristicFileList.add(file);
            }
            characteristicListView.setAdapter(new ShopCharacteristicAdapter(characteristicFileList, this));
            characteristicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ArrayList<ImageItem> imageItemArrayList = new ArrayList<>();
                    for (ZFile file : characteristicFileList) {
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = file.getPicurl();
                        imageItem.name = file.getName();
                        imageItemArrayList.add(imageItem);
                    }

                    Intent intent = new Intent(ShopDetailActivity.this, ImagePreviewActivity.class);
                    intent.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, 0);
                    intent.putExtra("images", imageItemArrayList);
                    startActivity(intent);
                }
            });
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ScreenUtils.getScreenWidth(this) / 4 + 15);
            characteristicListView.setLayoutParams(layoutParams);
        }
    }

    private void initCommentView() {
        commentListView.setFocusable(false);
        if (shopDetail.getEvaluate() != null && shopDetail.getEvaluate().size() > 0) {
            commentMoreText.setVisibility(View.VISIBLE);
            commentListView.setAdapter(new CommentAdapter(shopDetail.getEvaluate(), this));
        }
    }

    class PicassoImageLoader implements ImageLoader {
        @Override
        public void displayImage(Activity activity, String path, ImageView imageView, int width, int height) {
            Picasso.with(activity)//
                    .load(path)//
                    .placeholder(R.mipmap.test)//
                    .error(R.mipmap.test)//
                    .resize(width, height)//
                    .centerInside()//
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)//
                    .into(imageView);
        }

        @Override
        public void displayImagePreview(Activity activity, String path, ImageView imageView, int width, int height) {

        }

        @Override
        public void clearMemoryCache() {
            //这里是清除缓存的方法,根据需要自己实现
        }
    }

}
